package com.macro.mall.wx.service.impl;

import com.alibaba.fastjson.JSON;
import com.macro.mall.common.util.HttpClient;
import com.macro.mall.wx.API.WxAPI;
import com.macro.mall.wx.sdk.WxBeanConfig;
import com.macro.mall.wx.service.GetAccessTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Service
public class GetAccessTokenServiceImpl implements GetAccessTokenService {
    @Autowired
    private WxBeanConfig wxBeanConfig;
    @Override
    public String getAccessToken() {
        StringBuilder sb = new StringBuilder(WxAPI.GET_ACCESS_TOKEN);
        Map<String, String> param = new HashMap<>();
        param.put("grant_type","client_credential");
        param.put("appid",wxBeanConfig.getAppId());
        param.put("secret",wxBeanConfig.getSecret());
        try {
            String result = HttpClient.get(sb.append(HttpClient.buildMap(param)).toString());
            Map<String, String> map = JSON.parseObject(result, Map.class);
            if(StringUtils.isNotBlank(map.get("access_token"))){
                return map.get("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
